import {
  Component,
  OnInit,
  ContentChildren,
  AfterContentInit,
  AfterViewInit,
  ViewChild,
  ElementRef,
  ViewChildren,
  QueryList,
  Input,
  Output,
  EventEmitter
} from '@angular/core';
import {UploadGroupService} from './uploadgroup.service';
import {NzMessageService} from 'ng-zorro-antd';

@Component({
  selector: 'uploadgroup',
  templateUrl: './uploadgroup.component.html',
  styleUrls: ['./uploadgroup.component.scss'],
  providers: [UploadGroupService]
})

export class UploadGroupComponent implements OnInit {
  // @Input() piclist=[];//图片列表
  @Input() piclist = [];//图片列表
  @Input() length = 4;//总共长度
  @Input() size = 500;//文件大小 500K
  @Input() uploadname = "上传图片";
  @Input() fileList = [];
  @Input() edit = false;
  @Output() piclistChange = new EventEmitter();
  @Output() fileListChange = new EventEmitter();
  @Output() picDeleteChange = new EventEmitter();
  @Output() deletefun = new EventEmitter();
  @Output() addfun = new EventEmitter();
  @ViewChild('upload') upload: ElementRef;//通过@ViewChild获取元素
  @Input() readonly;
  @Input() readonly2;
  index = null;
  count = 0;

  uploadclick(i) {
    ++this.count;
    if(this.count == 1) {
      this.index = i;
      this.upload.nativeElement.click();
      this.count = 0;
    }
  }

  constructor(private _message: NzMessageService) {
  }

  delete(index,where?) {
    this.piclist[index]['src'] = '';
    this.fileList[index] = 'pic';
    this.fileListChange.emit(this.fileList);
    this.piclistChange.emit(this.piclist);
    if(where) {
      this.picDeleteChange.emit(where);
    }
    this.deletefun.emit();
  }


  addImage(e) {
    var target = e.target;
    let file = target.files[0];
    if (!file) {
      return false;
    }
    var size = file.size;
    var type = file.type;
    let typecheck = new RegExp(/image/i);
    if (!typecheck.test(type)) {
      this._message.create('error', '请上传图片格式');
      return false;
    }
    if (size > 1024 * this.size) {
      this._message.create('error', '最大可上传' + this.size + 'KB的图片');
      return false;
    }
    var reader = new FileReader();
    reader.readAsDataURL(file);
    //var uploadlist=this.uploadlist;
    reader.onload = (e) => {
      // this.piclist.push({src: reader.result});
      // this.piclist[i].push({src: reader.result});
      this.piclist[this.index]['src'] = reader.result;
    }
    this.fileList[this.index] = file;
    this.fileListChange.emit(this.fileList);
    this.addfun.emit();
  }

  ngOnInit() {

  }
}
